/* 商品列表页脚本
 ** 2020-10-10
 ** by Molly
 */


var mainVm = new Vue({
  el: '.list-container',
  data: {
    loadFlag: true,
    url: {
      goods_products: '/antacom/data.Goods/getGoods',
      path_list: MALL.Common.url.path_list,
    },
    list: listData ? listData : {},
    info: false,
    pageList: [],
    para: false,
    paraClose: {},
    path: '',
    path_sp: '-',
    goodsList: [],
    dropdown: {
      order: false,
      page_top: false,
      page_bot: false,
    },
    title: '',
    form: {
      p: 1,
      k: '',
      o: '',
      para: '',
    },
    goodsFlag: true,
  },
  mounted: function () {
    this.listInit();
  },
  methods: {
    listInit: function (callbak) {
      // 初始数据处理
      for (var x in this.list) {
        switch (x) {
          case 'info':
            this.info = this.list[x];
            if (this.list[x] && this.list[x]._page > 0) {
              var _pageList = [];
              for (var i = 1; i <= this.list[x]._page; i++) {
                _pageList.push(i);
              }
              this.pageList = _pageList;
            }
            if (this.list[x].keywords) this.$set(this.form, 'k', this.list[x].keywords);
            if (this.list[x]._p) {
              this.$set(this.form, 'p', parseInt(this.list[x]._p));
              this.$set(this.info, '_p', parseInt(this.list[x]._p));
            } else {
              this.$set(this.info, '_p', 1);
            }
            break;
          case 'para':
            this.para = this.list[x];
            var _title = ['', '所有', '商品'];
            if (this.list[x].bread) {
              var _bread = this.list[x].bread;
              for (var y in _bread) {
                if (_bread[y].code == 5) _title[2] = _bread[y].name;
                if (_bread[y].code == 10) {
                  _title[0] = _bread[y].name.length == 1 ? _bread[y].name + '子' : _bread[y].name;
                }
              }
            }
            this.title = _title.join('');
            var _newbar = this.para.newbar ? this.para.newbar : [],
              _count = 0;
            for (var y in _newbar) {
              if (_count < 2) this.$set(this.paraClose, y, 1);
              else this.$set(this.paraClose, y, 0);
              _count++;
            }
            break;
          case 'path':
            this.path = this.list[x];
            this.$set(this.form, 'para', this.list[x]);
            break;
          case 'path_sp':
            this.path_sp = this.list[x];
            break;
          case 'id_goods':
            // 商品数据
            this.getGoods();
            break;
          default:
        }
      }
      this.$set(this.form, 'para', this.setPara(this.form.para));
      this.backupForm();
      this.$nextTick(function () {
        if (callbak) loadCallbak();
        $('body,html').scrollTop(0);
      });
      /*this.$nextTick(() => {
				if(callbak) loadCallbak();
				$('body,html').scrollTop(0);
			});	*/
    },
    toggleSelector: function (key) {
      // 筛选项菜单收起与展开
      if (key == '') return false;
      var _active = this.paraClose[key];
      this.$set(this.paraClose, key, _active == 1 ? 0 : 1);
    },
    toggleDropdown: function (key) {
      // 下拉浮窗显示与隐藏
      for (var x in this.dropdown) {
        if (key && x == key) this.$set(this.dropdown, x, !this.dropdown[x]);
        else this.$set(this.dropdown, x, false);
      }
    },
    setPara: function (path) {
      // para转成object对象
      if (typeof path == 'object') return path;
      if (path == '') return '';
      var _para = {},
        _path = path.split(this.path_sp);
      for (var i in _path) {
        if (_path[i].length == 0) continue;
        var _itm = {
          code: _path[i].substr(0, 1),
          sub: _path[i].substr(1, _path[i].length - 1).split('_'),
        };
        if (_itm.sub.length > 0) _para[_itm.code] = _itm.sub;
      }
      return _para;
    },
    backupForm: function () {
      // 改变form数值前先备份旧数据
      this.bak_form = JSON.stringify(this.form);
    },
    // 改变页面数据的点击操作
    changeTag: function (path) {
      // 点击筛选项，目前单选
      if (!this.goodsFlag || !this.loadFlag) return false;
      this.backupForm();
      var _path = path,
        _para = this.form.para == '' ? {} : this.form.para;
      if (_path != '') {
        var _code = _path.substr(0, 1),
          _id = _path.substr(1, _path.length - 1);
        if (_para[_code] && _para[_code].length > 0) {
          var isCreate = false;
          for (var x in _para[_code]) {
            if (_para[_code][x] == _id) {
              isCreate = true;
              break;
            }
          }
          if (!isCreate) {
            _para[_code].push(_id);
          }
        } else {
          _para[_code] = [];
          _para[_code] = _id.split('_');
        }
      }
      this.$set(this.form, 'para', _para);
      this.$set(this.form, 'p', 1);
      this.loadPage();
    },
    removeTag: function (para) {
      // 移除筛选标签
      if (!this.goodsFlag || !this.loadFlag) return false;
      this.backupForm();
      this.$set(this.form, 'para', para && para != '' ? this.setPara(para) : '');
      this.$set(this.form, 'p', 1);
      this.loadPage();
    },
    orderby: function (order) {
      // 排序方式
      if (!this.goodsFlag || !this.loadFlag) return false;
      if (order == this.form.o) return false;
      this.backupForm();
      this.$set(this.form, 'o', order);
      this.$set(this.form, 'p', 1);
      this.toggleDropdown('');
      this.loadPage();
    },
    pageClick: function (type, value) {
      // 分页
      if (!this.goodsFlag || !this.loadFlag) return false;
      this.backupForm();
      var _totalPage =
          this.info && this.info._page && this.info._page >= this.info._p
            ? this.info._page
            : this.form.p,
        _curPage = this.form.p,
        _nextPage = false;
      switch (type) {
        case 'num':
          _nextPage = parseInt(value);
          break;
        case 'btn':
          if (value == 'prev') _nextPage = _curPage - 1;
          else if (value == 'next') _nextPage = _curPage + 1;
          break;
        default:
      }
      var _errMsg = '';
      if (_nextPage >= 1 && _nextPage <= _totalPage && _nextPage != _curPage) _errMsg = false;
      else if (_nextPage == _curPage) _errMsg = '当前已经是第' + _curPage + '页了';
      else if (type == 'btn' && _nextPage < 1) _errMsg = '当前已经是第1页了';
      else if (type == 'btn' && _nextPage > _totalPage) _errMsg = '当前已经是最后一页了';
      else _errMsg = '页码错误';
      this.toggleDropdown('');
      if (_errMsg && _errMsg != '') {
        MALL.Common.message({ text: _errMsg, time: 2000 });
        return false;
      }
      this.$set(this.form, 'p', _nextPage);
      this.loadPage();
    },
    reset: function () {
      // 重置
      if (!this.goodsFlag || !this.loadFlag) return false;
      this.backupForm();
      this.$set(this.form, 'para', '');
      this.$set(this.form, 'p', 1);
      this.loadPage();
    },
    // 加载新页面
    loadPage: function () {
      if (!this.goodsFlag || !this.loadFlag) return false;
      var _getParam = [],
        _postParam = {},
        that = this,
        _newPath = that.url.path_list,
        _para = '';
      for (var x in this.form) {
        if (this.form[x] == '') continue;
        var _item = false;
        if (x == 'para') {
          var _para = [];
          for (var y in this.form[x]) {
            if (this.form[x][y].length <= 0) continue;
            _para.push(y + this.form[x][y].join('_'));
          }
          if (_para.length > 0) _para = _para.join('-'); //_item
        } else {
          _item = this.form[x];
        }
        if (_item != false) {
          (_postParam[x] = _item), _getParam.push(x + '=' + _item);
        }
      }
      _newPath =
        that.url.path_list + _para + (_getParam.length > 0 ? '?' + _getParam.join('&') : '');
      MALL.Common.showLoading();
      this.loadFlag = false;
      $.ajax({
        type: 'POST',
        url: that.url.path_list + _para,
        data: _postParam,
        dataType: 'json',
        success: function (res) {
          MALL.Common.hideLoading();
          that.loadFlag = true;
          if (
            (res.para || res.info || res.id_goods) &&
            'undefined' != typeof document.body.style.maxHeight &&
            !(
              navigator.appName == 'Microsoft Internet Explorer' &&
              navigator.appVersion.match(/7./i) == '7.'
            )
          ) {
            that.list = res;
            var stateObject = {},
              title = $('title').html(),
              newUrl = _newPath;
            history.pushState(stateObject, title, newUrl);
            that.listInit(true);
            return false;
          }
          location.href = _newPath;
        },
        error: function (res) {
          MALL.Common.hideLoading();
          that.loadFlag = true;
          location.href = _newPath;
        },
      });
    },
    // 获取商品列表
    getGoods: function () {
      if (!this.goodsFlag || !this.loadFlag) return false;
      var that = this,
        _list = this.list.id_goods,
        _ids = [];
      for (var x in _list) {
        _ids.push(_list[x]);
      }
      if (_ids.length == 0) return false;
      this.goodsFlag = false;
      $.ajax({
        type: 'POST',
        url: that.url.goods_products,
        async: false,
        data: { id_goods: _ids.join(',') },
        dataType: 'json',
        success: function (res) {
          that.goodsFlag = true;
          if (res.status == '1') {
            var _goods = res.data && res.data.length > 0 ? res.data : [];
            for (var x in _goods) {
              if (_goods[x]) {
                _goods[x].startIdx = 0;
                _goods[x].hover = false;
                _goods[x].image = _goods[x].info.image;
                for (var y = _goods[x].child.length - 1; y >= 0; y--) {
                  try {
                    if (
                      !_goods[x].child[y].image ||
                      _goods[x].child[y].image.small.indexOf('_empty') >= 0
                    ) {
                      _goods[x].child.splice(y, 1);
                    }
                  } catch (error) {
                    console.error(error);
                  }
                }
              }
            }
            that.goodsList = _goods && _goods.length > 0 ? _goods : that.goodsList;
          }
        },
        error: function (res) {
          that.goodsFlag = true;
        },
      });
    },
    // 商品组操作
    hoverGoodsItem: function (goodsIdx, hover, event) {
      if (goodsIdx < 0) {
        return false;
      }
      var goodsItem = this.goodsList[goodsIdx];

      goodsItem.hover = hover || false;
      if (!hover) {
        goodsItem.image = goodsItem.info.image;
      }
      this.$set(this.goodsList, goodsIdx, goodsItem);
      this.$nextTick(function () {
        if (!hover) {
          var image = $(event.target).find('.J_goods_img').eq(0);
          image.attr('src', image.attr('original'));
        }
      });
    },
    hoverGoodsThumb: function (goodsIdx, thumbIdx, hover, event) {
      if (goodsIdx < 0 || thumbIdx < 0) {
        return false;
      }
      var goodsItem = this.goodsList[goodsIdx];

      goodsItem.child[thumbIdx].hover = hover || false;
      goodsItem.image = hover ? goodsItem.child[thumbIdx].image.normal : goodsItem.info.image;
      this.$set(this.goodsList, goodsIdx, goodsItem);

      this.$nextTick(function () {
        if (hover) {
          var image = $(event.target).parents('.J_goods_item').find('.J_goods_img').eq(0);
          image.attr('src', $(event.target).find('img').eq(0).attr('data'));
        }
      });
    },
    clickGoodsThumb: function (goodsIdx, type, event) {
      if (goodsIdx < 0) {
        return false;
      }
      var goodsItem = this.goodsList[goodsIdx];

      switch (type) {
        case 1:
          if (goodsItem.startIdx > 0) {
            goodsItem.startIdx--;
          }
          break;
        case 2:
          if (goodsItem.startIdx + 5 < goodsItem.child.length) {
            goodsItem.startIdx++;
          }
          break;
      }
      this.$set(this.goodsList, goodsIdx, goodsItem);
      this.$nextTick(function () {
        var list = $(event.target).siblings('.J_thumbs_list').find('li');
        var image = $(event.target).parents('.J_goods_item').find('.J_goods_img').eq(0);

        image.attr('src', list.eq(goodsItem.startIdx).find('img').attr('data'));
        if (list.find('img[original]').length > list.find('img[src]').length) {
          for (var i = 0; i < list.length; i++) {
            var _itpic = list.eq(i).find('img');
            _itpic.attr('src', _itpic.attr('original'));
          }
        }
      });
    },
  },
});
window.onload = function () {
  loadCallbak();
};
function loadCallbak() {
  pageResizeInit();
  $('.main-container .loading').removeAttr('src');
  $('.loading').scrollLoading();
}
function pageResizeInit() {
  /* 页面窗口resize时调用函数，各页面内重新写并覆盖
   ** ！！！ mall.common.js中的window.onresize函数已调用
   */
}
